<template>
  <div>
    <van-search @input="search" v-model="key" placeholder="请输入搜索关键词" />

    <!-- 热门搜索盒子 -->
    <div v-if="key === ''" class="search_wrap">
      <div class="hot_title">热门搜索</div>
      <div class="hot_name_wrap">
        <span
          v-for="(item, index) in hotList"
          :key="index"
          @click="search(item.first)"
          class="hot_item"
          >{{ item.first }}</span
        >
      </div>
    </div>

    <!-- 最佳匹配盒子 -->
    <div v-else class="search_wrap">
      <div class="hot_title">最佳匹配</div>
      <van-cell-group>
        <music-cell
          v-for="item in searchList"
          :key="item.id"
          :id="item.id"
          :title="item.name"
          :singerName="item.artists[0].name"
        />
      </van-cell-group>
    </div>
  </div>
</template>

<script>
// 导入接口
import { hotListAPI, searchAPI } from '@/api/search'
export default {
  name: 'MySearch',
  data () {
    return {
      key: '',
      hotList: [],
      searchList: [],
      timer: null
    }
  },
  methods: {
    search (name) {
      // 如果输入内容为空，没必要往下执行
      if (name === '') return

      clearTimeout(this.timer)
      this.timer = setTimeout(async () => {
        // 赋值给搜索框
        this.key = name
        // 发请求获取最佳匹配
        const res = await searchAPI({
          keywords: this.key
        })
        this.searchList = res.result.songs
      }, 200)
    }
  },
  async created () {
    const res = await hotListAPI()
    // console.log(res)
    this.hotList = res.result.hots
  }
}
</script>

<style scoped>
/* 搜索容器的样式 */
.search_wrap {
  padding: 10px;
}

/*热门搜索文字标题样式 */
.hot_title {
  font-size: 12px;
  color: #666;
}

/* 热搜词_容器 */
.hot_name_wrap {
  margin: 10px 0;
}

/* 热搜词_样式 */
.hot_item {
  display: inline-block;
  height: 35px;
  margin-right: 20px;
  margin-bottom: 15px;
  padding: 0px 14px;
  font-size: 14px;
  line-height: 35px;
  color: #333;
  border-color: #d3d4da;
  border-radius: 20px;
  border: 1px solid #d3d4da;
}
</style>
